//
//  ST_PinterestHomeDataAdapter.swift
//  btvideo
//
//  Created by mac on 2020/5/18.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import HandyJSON
import SwiftyJSON
import SwiftyUserDefaults
import SwifterSwift


@objc protocol ST_PinterestHomeDataAdapterViewDelegate {
    
    func reload_view_from_data_adapter(currentCount:Int)
    
    func fail_load_data(code:Int,error:String)
    
    @objc optional func refreshCell(groupId:String)
}



class ST_PinterestHomeDataAdapter: NSObject,ST_InteractivePairsProtocol {
    
    override init() {
        super.init()
        
//        NotificationCenter.default.addObserver(self, selector: #selector(receive_liked_somebody_handle(notification:)), name: Notification.Name.liked_somebody, object: nil)
//
//
//        NotificationCenter.default.addObserver(self, selector: #selector(like_ignore_hanlde(noti:)), name: Notification.Name.ignore_somebody, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(showed_noti_handle(noti:)), name: Notification.Name.showedSomeOne, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(like_ignore_hanlde(noti:)), name: Notification.Name.ban_somebody, object: nil)
        
    }
    
    @objc fileprivate func showed_noti_handle(noti:Notification){
        
        
        
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController ,let id = info["id"] as? String else{
            return
        }
        
////        可交互的个人中心 不需要Remove 因为调用 fetch_next_user 会导致Remove
//        if (vc is ST_InteractivePairsCenterController) == false && (vc is ST_NextST_InteractivePairsCenterController) == false{
//            
            self.delete(itemId: id)
//        }
    }
    
    @objc func like_ignore_hanlde(noti:Notification){
        
        //         ["accid": self.accid,"likeOption":true]
        let json = JSON.init(noti.userInfo ?? "")
        
        let accid = json["accid"].stringValue
        
        self.delete(itemId: accid)
        
    }
    
    @objc fileprivate func receive_liked_somebody_handle(notification:Notification){
        
        
        let json = JSON(notification.userInfo ?? "")
        
        
        self.delete(itemId: json["id"].stringValue)
    }
    
    //    MARK: - private Set Properties
    
    private(set) var data_array = [ST_PinterestHomeCellModel]()
    
    private(set) var currentPage = 0
    
    private(set) var existSet = Set<String>()
    
    private(set) var jsonWhereStr:String?
    //    MARK: - Public Properties
    
    var searchedResult = false
    
    var delegate:ST_PinterestHomeDataAdapterViewDelegate?
    
    
    /**个人主页跳转下一页使用*/
    var currPairsUserId:String?
    
    
    var searchParam = [String:Any]()
    //    MARK: - Public Method
    
    func fetch_next_user(remove:Bool)->ST_PinterestHomeCellModel?{
        
        guard let id = currPairsUserId,let currPairsUserIndex = data_array.firstIndex(where: { (m) -> Bool in
            return m.accid == id
        }) else { return nil }
        
        var idx = currPairsUserIndex
        
        while idx < data_array.count {
            
            idx += 1
            
            if let item = data_array[safe:idx]{
                
                if item.type.rawValue < 2{
                    
                    if let last = currPairsUserId , remove{
                        self.delete(itemId: last)
                    }
                    
                    
                    currPairsUserId = item.accid
                    
                    if data_array.count - Int(idx.uInt) < 3{
                        
                        self.load_data_from_remote()
                    }
                    
                    
                    return item
                }else{
                    self.delete(itemId: item.accid)
                }
            }
        }
        return nil
    }
    
    func clear_data(){
        
        
        currentPage = 0
        
        self.data_array.removeAll()
        
        self.delegate?.reload_view_from_data_adapter(currentCount: 0)
    }
    
    func delete(itemId:String)  {
        
        //print("崩溃BUG 删除之前多少条",self.data_array.count)
        
        self.data_array.removeFirst { (cellModel) -> Bool in
            return cellModel.accid == itemId
        }
        
        //print("崩溃BUG 删除了 数据:",itemId)
        
        //print("崩溃BUG 删除之后多少条",self.data_array.count)
        
        self.delegate?.reload_view_from_data_adapter(currentCount: 21)
    }
    
    
    func reloadData()  {
        
        currentPage = 0
        
        load_data_from_remote()
    }
    
    func load_data_from_remote()  {
        
        
        currentPage += 1
        
        var param = ["page":currentPage,
                     "size":20] as [String : Any]
        
        
        if currentPage == 1{
            jsonWhereStr = nil
        }
        
        if let jsonStr = jsonWhereStr,jsonStr.count > 0{
            param.updateValue(jsonStr, forKey: "json_where")
        }
        
        if searchParam.count > 0{
            param += searchParam
            param.updateValue("1", forKey: "select_way")
        }else{
            param.removeValue(forKey: "select_way")
        }
        
//        debugPrint("搜索 参数 传递:",param)
//        print("搜索 参数 传递:",param)
        
        
        JVrequest(PH.RecommendFeedV32Api,parameters:param, success: { (json) in
            
            print("首页数据：",json["data"])
            
            self.jsonWhereStr = json["data"]["json_where"].string
            
            let aArray = ST_PinterestHomeCellModel.describe(json_array: json["data"]["list"].arrayValue)
            
            var addArray = [ST_PinterestHomeCellModel]()
            
//            第一页重新计算重复
            if self.currentPage < 2{
                self.existSet.removeAll()
            }
            
            aArray.forEach { (item) in
                
//                重复了
                if self.existSet.contains(item.accid) == false{
                    addArray.append(item)
                    self.existSet.update(with: item.accid)
                }
            }
            
//            添加卡片
            var handledArray = addArray
//            搜索不添加卡片
            if !self.searchedResult {
                handledArray = self.insertGuidance(originalArray: addArray,currentPage:self.currentPage , completeUserExtension: json["data"]["user_info"]["information_is_perfect"].boolValue)
            }
            
            if self.currentPage == 1{
                self.data_array = handledArray
                
                if handledArray.count < 20{
                    self.load_data_from_remote()
                }
                
            }else{
                self.data_array += handledArray
            }
            self.delegate?.reload_view_from_data_adapter(currentCount: aArray.count)
            
        }) { (code, err) in
            
            self.delegate?.fail_load_data(code: code, error: err)
            
        }
        
        
        
    }
    
    
    
    
}


//MARK: - private Model
extension ST_PinterestHomeDataAdapter{
    
    
    
    fileprivate func insertGuidance(originalArray:[ST_PinterestHomeCellModel],currentPage:Int = 1,completeUserExtension:Bool = true)->[ST_PinterestHomeCellModel]{
        
        if originalArray.count < 3{
            return originalArray
        }
        let guidance = ST_PinterestHomeCellModel()
        
        guidance.accid = UUID().uuidString
        
        guidance.size = CGSize.init(width: 170, height: 210)
        
        let row = currentPage%4
        
        switch row {
        case 1:
            guidance.type = .Guidance_特质
            guidance.guidanceImageName = "首页_卡片_添加特质"
        case 2:
            guidance.type = .Guidance_照片
            guidance.guidanceImageName = "首页_卡片_更多照片"
        case 3:
            //            3.如果用户填写了“个人介绍”，“添加个人介绍”取消不显示
            if ST_PinterestHomeGuidanceManager.shared.get_hidden_add_intro(){
                return originalArray
            }
            
            guidance.type = .Guidance_自我介绍
            guidance.guidanceImageName = "首页_卡片_自我介绍"
        default:
            //            4.如果用户完成了所有“个人资料”，“完善个人资料”取消不显示
            if completeUserExtension{
                return originalArray
            }
            guidance.type = .Guidance_个人资料
            guidance.guidanceImageName = "首页_卡片_完善资料"
        }
        
        var array = originalArray
        
        array.insert(guidance, at: 2)
        
        return array
    }
    
}
